package com.rotai.hw.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TestActivity extends AppCompatActivity {

    private static final String TAG = "TestActivity";

    @Bind(R.id.et_prot)
    EditText etProt;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.btn_set)
    Button btnSet;
    @Bind(R.id.btn_open)
    Button btnOpen;
    @Bind(R.id.btn_send)
    Button btnSend;
    @Bind(R.id.btn_receive)
    Button btnReceive;
    @Bind(R.id.text_receive)
    TextView textReceive;
    @Bind(R.id.btn_sendCmd)
    Button btnSendCmd;
    @Bind(R.id.btn_sendCmdClose)
    Button btnSendCmdClose;


    protected SerialPort mSerialPort;
    protected InputStream mInputStream;
    protected OutputStream mOutputStream;

    private String prot = "ttyHSL1";
    private int baudrate = 38400;
    private static int i = 0;
    public static boolean flag = false;
    private StringBuilder sb;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                textReceive.setText(textReceive.getText().toString().trim() + sb.toString());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e(TAG, "程序初始化");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        ButterKnife.bind(this);
        openSerialPort();
        sendCmd();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭串口
        closeSerialPort();
    }

    /**
     * 设置串口
     */

    private void setSerialInfo() {
        prot = TextUtils.isEmpty(etProt.getText().toString().trim()) ? prot
                : etProt.getText().toString().trim();
        baudrate = Integer.parseInt(TextUtils.isEmpty(etNum.getText()
                .toString().trim()) ? "38400" : etNum.getText()
                .toString().trim());
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.btn_set, R.id.btn_open, R.id.btn_send, R.id.btn_receive, R.id.btn_sendCmd, R.id.btn_sendCmdClose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_set://设置串口
                setSerialInfo();
                break;
            case R.id.btn_open://打开串口
                openSerialPort();
                break;
            case R.id.btn_send://发送串口数据
                sendSerialDate();
                break;
            case R.id.btn_receive://关闭串口
                closeSerialPort();
                break;
            case R.id.btn_sendCmd:
                sendCmd();
                //                sendCmd1();
                break;
            case R.id.btn_sendCmdClose:
                sendCmdClose();
                break;
        }
    }

    /**
     * 发送关闭心率采集串口指令
     */
    private void sendCmdClose() {
        Log.e(TAG, "发送关闭采集指令");
        byte[] c = hexStringToBytes("0x88");
        if (mSerialPort != null) {
            try {
                mOutputStream.write(c);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送串口指令第二种方式
     */
    private void sendCmd1() {
        Log.e(TAG, "打开开启采集指令");
        byte[] b = hexStringToBytes("0x8A");
        try {
            mOutputStream.write(b);
            receiveSerialDate();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将输入的16进制string转成字节
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    /**
     * 发送打开心率采集串口指令
     */
    private void sendCmd() {
        Log.e(TAG, "发送指令");
        byte[] a = {(byte) 0x8A};
        try {
            mOutputStream.write(a);
            receiveSerialDate();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 打开串口
     */

    private void openSerialPort() {
        Log.e(TAG, "打开串口");
        try {
            mSerialPort = new SerialPort(new File("/dev/" + prot), baudrate, 0);
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();
            flag = true;

        } catch (SecurityException e) {
            e.printStackTrace();
            Log.i("test——serial", "打开失败");
        } catch (IOException e) {
            Log.i("test——serial", "打开失败");
            e.printStackTrace();
        }
        Log.i("test——serial # flag", "" + flag);
    }

    /**
     * 发送串口数据
     */

    private void sendSerialDate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    Log.i("test——serial", "发送串口数据");
                    try {
                        i++;
                        byte[] bytes = ("ok").getBytes();
                        mOutputStream.write(bytes);
                        mOutputStream.flush();
                        Log.i("test——serial", "发送成功:1" + i);
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        Log.i("test——serial", "发送失败");
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 接收串口数据
     */

    private void receiveSerialDate() {
        Log.e(TAG, "接收串口数据");
        sb = new StringBuilder();
        // 接收
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    int size;
                    try {
                        byte[] buffer = new byte[76];
                        if (mInputStream == null) {
                            return;
                        }
                        size = mInputStream.read(buffer);

                        if (size > 0 && flag) {

                            if (buffer[0] == (byte) 0xff) {
                                byte[] rateByte = new byte[64];
                                for (int j = 0; j < 64; j++) {
                                    rateByte[j] = (byte) -buffer[j + 1];
                                    Log.e(TAG, "字节数组rateByte中的元素是：" + rateByte[j]);
                                }

                                //                                int[] a = new int[64];
                                //                                for (int j = 0; j < 64; j++) {
                                //                                    a[j] = Integer.parseInt(String.valueOf(-rateByte[j]), 16);
                                //                                    Log.e(TAG, "元素是"+a[j] );
                                //                                }
                            }


                            //                            String s = bytesToHexString(buffer);
                            //                            sb.append(s).append(",");
                            //                            Log.e(TAG, "接收到的信息是" + s);
                            //                            handler.sendEmptyMessage(1);
                        }
                        Thread.sleep(100);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    /**
     * 字节转字符
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        Log.e(TAG, "关闭串口");
        //        Log.i("test——serial", "关闭串口");
        i = 0;
        try {
            if (mSerialPort != null) {
                mSerialPort.close();
                Log.i("test——serial", "关闭串口");
            }

            if (mInputStream != null) {
                mInputStream.close();
                Log.i("test——serial", "关闭输入流");
            }
            if (mOutputStream != null) {
                mOutputStream.close();
                Log.i("test——serial", "关闭输出流");
            }
            flag = false;
            Log.i("test——serial", "串口关闭成功");
        } catch (IOException e) {
            Log.i("test——serial", "关闭串口失败");
            e.printStackTrace();
        }
    }
}
